package com.czq.cn.service.impl;

import com.czq.cn.config.JwtUtils;
import com.czq.cn.entity.SysUser;
import com.czq.cn.service.UserService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {


    @Resource
    private AuthenticationManager authenticationManager;

    @Override
    public Map<String, String> login(SysUser user) {

        try {
            //自动会进行对比密码匹配
            Map<String,String> result = new HashMap<>();

            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            user.getUsername(),
                            user.getPassword())
            );

            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String token = JwtUtils.generateToken(userDetails);
            result.put("token",token);
            result.put("status","success");
            return result;
        }catch (BadCredentialsException e){
            throw new BadCredentialsException("用户名或密码错误");
        }
    }
}
